<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2022/10/27
 * Time: 13:51:22
 */

namespace app\common\service\ChannelCouponService;

use app\model\BbcModel\ChannelCoupon;
use app\Normal;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsBrand;

class ChannelCouponService
{
    public function couponLists( array $param): array{
        $page = (isset($param['page']) && $param['page'] != '') ? $param['page'] : 1;
        $limit = (isset($param['limit']) && $param['limit'] != '') ? $param['limit'] : 20;
        $where = [
            ['cid','=',$param['cid']],
            ['df','=',0],
        ];
        if(isset($param['name']) && $param['name'] != ''){
            $where[] = ['name','like',"%{$param['name']}%"];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status','=',$param['status']];
        }
        $data_lists = ChannelCoupon::instance()->where($where)->page((int)$page)->limit((int)$limit)->order('cd desc')->field('id,type,name,is_expiration,begindate,enddate,cd,status,sub_amount,min_amount')->select()->toArray();
        foreach ($data_lists as $k=>$v){
            if($v['min_amount'] == 0){
                $data_lists[$k]['details'] = '无门槛优惠'.$v['sub_amount'];
            }else{
                $data_lists[$k]['details'] = '满'.$v['min_amount'].'优惠'.$v['sub_amount'];
            }
            if($v['is_expiration'] == 1){ //无限制
                $data_lists[$k]['expiration'] = '无限制';
            }else{
                $data_lists[$k]['expiration'] = date('Y-m-d',$v['begindate']) . '至' . date('Y-m-d',$v['enddate']);
            }
            $data_lists[$k]['cd'] = date('Y-m-d H:i:s',$v['cd']);
            if($v['status'] == 1){
                $data_lists[$k]['status_text'] = '待开始';
            }else if($v['status'] == 2){
                $data_lists[$k]['status_text'] = '进行中';
            }else{
                $data_lists[$k]['status_text'] = '已结束';
            }
        }
        $total = ChannelCoupon::instance()->where($where)->count();
        return Normal::returnCode(Normal::SUC,'获取成功',['list'=>$data_lists,'total'=>$total]);
    }

    public function addCoupon( array $param): array{
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'优惠券名称不能为空');
        }
        $param['coupon_type'] = $param['coupon_type'] ?? 0;
        $param['rule_type'] = 1; //只有自动发放
        if($param['is_expiration'] == 1){ //无限制
            $param['begindate'] = '';
            $param['enddate'] = '';
            $param['status'] = 2;
        }else{
            $param['begindate'] = strtotime($param['begindate']);
            $param['enddate'] = strtotime($param['enddate']);
            if($param['enddate'] <= time()){
                return Normal::returnCode(Normal::FAIL,'优惠券结束时间不能小于当前时间');
            }

            if($param['begindate'] <= time() && time() <= $param['enddate']){
                $param['status'] = 2;
            }else if($param['begindate'] > time()){
                $param['status'] = 1;
            }
        }
        /*if($param['is_addition'] == 1){ //不叠加
            $param['addition'] = 1;
        }else{
            if(!isset($param['addition'])){
                return Normal::returnCode(Normal::FAIL,'请选择需要叠加的活动');
            }
            if(count($param['addition']) == 2){
                $param['addition'] = 4;
            }else if($param['addition'][0] == 3){
                $param['addition'] = 2;
            }else{
                $param['addition'] = 3;
            }
        }*/
        if($param['type'] == 1){ //适用全场商品
            $param['type_value'] = '';
        }else{
            if(!isset($param['goods_ids'])){
                return Normal::returnCode(Normal::FAIL,'请选择指定商品');
            }
            $param['type_value'] = implode(',',$param['goods_ids']);
            $param['type'] = 2;
        }
        if(isset($param['explain']) && mb_strlen($param['explain']) > 50){
            return Normal::returnCode(Normal::FAIL,'使用说明不能超过50字');
        }
        if($param['min_amount'] <= $param['sub_amount']){
            return Normal::returnCode(Normal::FAIL,'满减金额需大于优惠金额');
        }
        $insertData['type']          = $param['type'];
        $insertData['name']          = $param['name'];
        $insertData['explain']       = $param['explain'] ?? '';
        $insertData['is_expiration'] = $param['is_expiration'];
//        $insertData['addition']      = $param['addition'];
        $insertData['min_amount']    = $param['min_amount'];
        $insertData['sub_amount']    = $param['sub_amount'];
        $insertData['rule_type']     = $param['rule_type'];
        $insertData['total']         = $param['total'] ?? 0;
        $insertData['cid']           = $param['cid'];
        $insertData['begindate']     = $param['begindate'];
        $insertData['enddate']       = $param['enddate'];
        $insertData['status']        = $param['status'];
        $insertData['type_value']    = $param['type_value'];
        $insertData['coupon_type']   = $param['coupon_type'];
        $insertData['cd']            = time();

        $res = ChannelCoupon::instance()->insert($insertData);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    public function couponInfo( array $param): array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少优惠券ID');
        }
        $info = ChannelCoupon::instance()->info(['id'=>$param['id'],'cid'=>$param['cid'],'_fields_'=>'id,type,type_value,name,explain,is_expiration,begindate,enddate,min_amount,sub_amount,total,status']);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'小B优惠券不存在');
        }
        if($info['type'] == 2){ //指定商品
            $coupon_goods_list = Goods::instance()->lists([['id','in',$info['type_value']],'_fields_'=>'id,name,skucode,class_id,brand_id,is_bonded,price_cost,tax_free,tax_rate,barcode,price,price_vip,price_market']);
            foreach ($coupon_goods_list as $key => $value){
                $goods_class = GoodsClass::instance()->where(['id'=>$value['class_id']])->find();
                $coupon_goods_list[$key]['goodsclassname'] = empty($goods_class)?'':$goods_class['name'];
                $goods_brand = GoodsBrand::instance()->where(['id'=>$value['brand_id']])->find();
                $coupon_goods_list[$key]['goodsbrandname'] = empty($goods_brand)?'':$goods_brand['name'];
                if($value['is_bonded'] == 0){
                    $coupon_goods_list[$key]['is_bonded'] = '普通';
                }else if($value['is_bonded'] == 1){
                    $coupon_goods_list[$key]['is_bonded'] = '保税';
                }else{
                    $coupon_goods_list[$key]['is_bonded'] = '海外直邮';
                }
                $coupon_goods_list[$key]['tax_free'] = $value['tax_free']==1?'是':'否';
            }
            $goods_list = array_values($coupon_goods_list);
            $info['goods_list'] = json_encode($goods_list);
        }else{
            $info['goods_list'] = '';
        }
        return Normal::returnCode(Normal::SUC,'获取成功',$info);
    }

    public function changeStatus( array $param): array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'优惠券ID不能为空');
        }
        $info = ChannelCoupon::instance()->info(['cid'=>$param['cid'],'id'=>$param['id'],'df'=>0]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'优惠券不存在');
        }
        if(!in_array($info['status'],[1,2])){
            return Normal::returnCode(Normal::FAIL,'当前优惠券不可结束');
        }
        $res = ChannelCoupon::instance()->edit(['id'=>$param['id']],['status'=>3]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }
}